package com.developteam.xnmall.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.developteam.xnmall.dao.CategoryMapper;
import com.developteam.xnmall.entity.CategoryVO;
import com.developteam.xnmall.service.CategoryService;
import com.developteam.xnmall.vo.ResStatus;
import com.developteam.xnmall.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    //    ObjectMapper也必须赋初始值的
//    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private ObjectMapper objectMapper;
    //StringRedisTemplate也是bean,要被注入的
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询分类列表（包含三个级别的分类）
     *
     * @return
     */
    public ResultVO listCategories() {
        List<CategoryVO> categoryVOS = null;
        //一、查询redis
        try {
            String categories = stringRedisTemplate.boundValueOps("categories").get();
            //1000个请求都会进入else，同时访问数据库
            //让这些请求顺序执行

            if (categories != null) {
                //redis中有，将数据转换成我们需要的类型
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, CategoryVO.class);
                categoryVOS = objectMapper.readValue(categories, javaType);

            } else {
//                synchronized (this) {  //锁当前类对象，service类在spring容器中是单例的，所以，1000个并发线程共用一个service实例
                //二、redis中没有，查数据库
                categoryVOS = categoryMapper.selectAllCategories();
                //把查到的类别列表转成json
                String str = objectMapper.writeValueAsString(categoryVOS);
                stringRedisTemplate.boundValueOps("categories").set(str, 1, TimeUnit.DAYS);
//                }
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (categoryVOS != null) {
            return new ResultVO(ResStatus.OK, "success", categoryVOS);
        } else {
            return new ResultVO(ResStatus.NO, "fail", null);
        }
    }

    /**
     * 查询所有一级分类，同时查询当前一级分类下销量最高的6个商品
     *
     * @return
     */
    public ResultVO listFirstLevelCategories() {
        List<CategoryVO> categoryVOS = categoryMapper.selectFirstLevelCategories();
        ResultVO resultVO = new ResultVO(ResStatus.OK, "success", categoryVOS);
        return resultVO;
    }

}
